package me.helllp.bootman.back.utils;

import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 数据库中的日期数据的处理
 * <br/>数据库中不允许使用date,time,datetime,所有的日期都用INTEGER表示
 * 
 * @author 林晓明
 *
 */
public class DbTypeUtils {
	private final static DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");
	
	private final static DateFormat TIME_FORMAT = new SimpleDateFormat("HHmmss");
	
	/**
	 * 获得当前的日期：yyyyMMdd格式
	 * 
	 * @return
	 */
	public static long getDate(){
		String date = DATE_FORMAT.format(new Date());
		
		return Long.parseLong(date);
	}
	
	/**
	 * 获得当前的时间：HHmmss格式
	 * 
	 * @return
	 */
	public static long getTime(){
		String date = TIME_FORMAT.format(new Date());
		
		return Long.parseLong(date);
	}
	
	/**
	 * 获得时间戳
	 * 
	 * @return
	 */
	public static long getDateTime(){
		return new Date().getTime();
	}
	
	private final static String CREATE_USER_ID 	= "createUserId";
	private final static String UPDATE_USER_ID 	= "updateUserId";
	private final static String CREATE_TIME		= "createTime";
	private final static String UPDATE_TIME		= "updateTime";
	
	/**
	 * 进行公共的属性设置 
	 * 
	 * @param o
	 */
	public static void setCommonProp(Object o) {
		// 得到类对象
		Class<? extends Object> userCla = o.getClass();

		/*
		 * 得到类中的所有属性集合
		 */
		Field[] fs = userCla.getDeclaredFields();

		String name = "";
		Long value = 0L;
		boolean isCreate = false;
		boolean needSet = false;
		
		Long dateTime = getDateTime();
		Long userId = LocalSessionFactory.getUserId();
		userId = userId == null ? 0L : userId;
		
		for (int i = 0; i < fs.length; i++) {
			isCreate = false;
			needSet = false;
			
			Field f = fs[i];
			name = f.getName();
			
			switch (name) {
			case CREATE_USER_ID:
				value = userId;
				needSet = true;
				isCreate = true;
				break;
			case UPDATE_USER_ID:
				value = userId;
				needSet = true;
				isCreate = false;
				break;
			case CREATE_TIME:
				value = dateTime;
				needSet = true;
				isCreate = true;
				break;
			case UPDATE_TIME:
				value = dateTime;
				needSet = true;
				isCreate = false;
				break;
			default:
				needSet = false;
				break;
			}
			
			if(isCreate){
				f.setAccessible(true); // 设置些属性是可以访问的
				try {
					needSet = f.get(o) == null;
				} catch (Exception e) {
					needSet = false;
				}
			}
			if(needSet){
				f.setAccessible(true); // 设置些属性是可以访问的
				try {
					f.set(o, value);
				} catch (IllegalArgumentException | IllegalAccessException e) {
				}
			}
		}
	}
}
